package com.baizhi.service.impl;

import com.baizhi.annotation.LogAnnotation;
import com.baizhi.dao.BzMenuMapper;
import com.baizhi.entity.BzMenu;
import com.baizhi.service.IBzMenuService;
import com.baizhi.vo.MenuVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜单管理 服务实现类
 * </p>
 *
 * @author lby
 * @since 2020-09-24
 */
@Service
public class BzMenuServiceImpl extends ServiceImpl<BzMenuMapper, BzMenu> implements IBzMenuService {
    @Autowired
    private BzMenuMapper menuMapper;

    @Override
    @LogAnnotation(content ="查询菜单数据")
    public List<BzMenu> selectMenus() {
        return menuMapper.selectMenus();
    }

    @Override
    public List<MenuVo> selectMenusByStream() {
        /**
         * 拥有所有数据 一级二级三级都有
         */
        List<BzMenu> bzMenus = menuMapper.selectList(null);

        /**
         * 1 先找到所有的一级菜单
         * 2 根据一级菜单找到所有二级 上一级的id==下一级父id
         * 3 根据二级菜单找到所有三级 上一级的id==下一级父id
         *
         * 递归
         */
        List<MenuVo> menuVoList = bzMenus.stream()
                .filter(bzMenu -> {
                    return bzMenu.getParentId() == 0;
                })
                .map(bzMenu -> {
//                    对象转化 BzMenu ---》Vo
                    MenuVo menuVo = new MenuVo();
                    BeanUtils.copyProperties(bzMenu, menuVo);
//                    根据一级id找二级  封装到集合属性中 去bzMenus集合中找
                    menuVo.setMenuList(getMenuList(menuVo,bzMenus));
                    return menuVo;
                }).collect(Collectors.toList());
        return menuVoList;
    }

    private List<MenuVo> getMenuList(MenuVo menuVo, List<BzMenu> bzMenus) {
        List<MenuVo> vos = bzMenus.stream()
                .filter(bzMenu -> {
                    return menuVo.getMenuId() == bzMenu.getParentId();
                })
                .map(bzMenu -> {
//                    bzMenu --> Vo
                    MenuVo menuVo1 = new MenuVo();
                    BeanUtils.copyProperties(bzMenu, menuVo1);
//                    根据二级找三级
                    menuVo1.setMenuList(getMenuList(menuVo1, bzMenus));
                    return menuVo1;
                }).collect(Collectors.toList());
        return vos;
    }
}
